package org.example.annotation;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * 自定义拦截器
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2021/8/24 20:23
 */
public class AppInterceptor implements HandlerInterceptor {

    /**
     * 请求进入时进行拦截，返回 true 时，表示继续往下走；
     * 返回 false 时, 表示停止后续的执行，即请求不会到达控制层.
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("进入拦截器,用户请求:" + requestURL);
        if (handler instanceof HandlerMethod) {
            //方法处理器, 请求的目标方法
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            //1: 获取目标方法上的指定注解,不存在时,返回 Null.
            MethodOperate methodOperate = handlerMethod.getMethodAnnotation(MethodOperate.class);
            if (methodOperate != null) {
                String desc = methodOperate.desc();
                System.out.println("\t目标方法存在 @MethodOperate 注解, desc=" + desc);
            }

            //2: 获取目标方法所在类上的指定主键, 不存在时, 返回 null.
            ClassOperate classOperate = handlerMethod.getMethod().getDeclaringClass().getAnnotation(ClassOperate.class);
            if (classOperate != null) {
                String[] value = classOperate.value();
                String desc = classOperate.desc();
                String vs = value != null ? Arrays.asList(value).toString() : "";
                System.out.println("\t目标方法所在的类存在 @ClassOperate 注解, desc=" + desc + ", value=" + vs);
            }

            // 3、获取目标方法及其类上的注解
            MultipleOperate multipleOperate1 = handlerMethod.getMethodAnnotation(MultipleOperate.class);
            MultipleOperate multipleOperate2 = handlerMethod.getMethod().getDeclaringClass().getAnnotation(MultipleOperate.class);
            if (multipleOperate1 != null) {
                String desc = multipleOperate1.desc();
                String[] value = multipleOperate1.value();
                String vs = value != null ? Arrays.asList(value).toString() : "";
                System.out.println("\t目标方法存在 @MultipleOperate 注解, desc=" + desc + ", value=" + vs);
            }
            if (multipleOperate2 != null) {
                String desc = multipleOperate2.desc();
                String[] value = multipleOperate2.value();
                String vs = value != null ? Arrays.asList(value).toString() : "";
                System.out.println("\t目标方法所在的类存在 @MultipleOperate 注解, desc=" + desc + ", value=" + vs);
            }
        }
        return true;
    }
}
